#include "formulaanalyse.h"
#include "easylogging/easylogging++.h"

FormulaAnalyse::FormulaAnalyse()
{

}

typedef exprtk::expression<double> expression_t;
typedef exprtk::parser<double> parser_t;

bool FormulaAnalyse::Result(QVector<Condition*> conditions, QString formula)
{
//    double x = 100;
//    double y = 0;
//    double z = 0;
    exprtk::symbol_table<double> symbol_table;
    for (int i = 0; i < conditions.count(); i++)
    {
        double value = conditions[i]->GetResult();
        LDEBUG<<"value is : " << value;
        LDEBUG<<"arg is : " << conditions[i]->GetArgName();
        symbol_table.add_variable(conditions[i]->GetArgName().toStdString(),value);
    }
//    symbol_table.add_variable("x", x);
//    symbol_table.add_variable("y", y);
//    symbol_table.add_variable("z", z);

    expression_t expression;
    expression.register_symbol_table(symbol_table);

    parser_t parser;
    LDEBUG<<"formula is :" << formula;
//    const char* formulaf = "(x and y) or z";
//    const char* formulaf = "x";
//    formula.toStdString()
    parser.compile(formula.toStdString(), expression);
//    parser.compile(formulaf, expression);

    LDEBUG << "FormulaAnalyse::Result :" << expression.value();

    if(expression.value() == 1)
    {
        return true;
    }

    return false;
}

double FormulaAnalyse::Result(QVector<Entity *> entitys, QString formula)
{
    exprtk::symbol_table<double> symbol_table;
    for (int i = 0; i < entitys.count(); i++)
    {
        double value = entitys[i]->GetResult();
        LDEBUG<<"value is : " << value;
        LDEBUG<<"arg is : " << entitys[i]->GetArgName();
        symbol_table.add_variable(entitys[i]->GetArgName().toStdString(),value);
    }

    expression_t expression;
    expression.register_symbol_table(symbol_table);

    parser_t parser;
    LDEBUG<<"formula is :" << formula;
    parser.compile(formula.toStdString(), expression);

    LDEBUG << "FormulaAnalyse::Result :" << expression.value();

    return expression.value();
}
